<template>
  <div class="page-container main-view">
    <el-row
      :gutter="0"
      v-show="dataContainer.showSearch"
      class="page-query-box"
    >
      <el-col :span="24" :xs="24">
        <el-form
          :model="dataContainer.form"
          ref="QueryFormRef"
          :inline="true"
          label-width="110px"
        >
          <el-row :gutter="0">
            <el-col :span="6" :xs="6">
              <el-form-item label="员工ID" prop="employeeId">
                <el-input
                  v-model="dataContainer.form.employeeId"
                  placeholder="请输入员工ID"
                  clearable
                  @clear="handleQuery"
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6" :xs="6">
              <el-form-item label="操作类型" prop="operationType">
                <el-input
                  v-model="dataContainer.form.operationType"
                  placeholder="请输入操作类型"
                  clearable
                  @clear="handleQuery"
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6" :xs="6">
              <el-form-item label="状态" prop="status">
                <el-select
                  v-model="dataContainer.form.status"
                  placeholder="请选择状态"
                  clearable
                  @clear="handleQuery"
                >
                  <el-option label="completed" value="completed" />
                  <!-- 添加其他状态选项 -->
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" :xs="6">
              <el-form-item label="日期范围" prop="dateRange">
                <el-date-picker
                  v-model="dataContainer.form.dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  :shortcuts="dateRangeShortcuts"
                  @change="handleDateRangeChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6" :xs="6">
              <el-form-item label=" ">
                <el-button type="primary" @click="handleQuery">
                  <SvgIcon
                    :style="'width:15px;height:15px;margin-right:5px;'"
                    name="svg:search-bt.svg"
                  ></SvgIcon>
                  查询
                </el-button>
                <el-button @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-col>
    </el-row>
    <div class="table-box content-container page-content-box">
      <div class="top-container">
        <div class="left">
          <!-- 移除检查超时订单按钮 -->
        </div>
        <div class="right">
          <el-button
            circle
            @click="dataContainer.showSearch = !dataContainer.showSearch"
          >
            <SvgIcon
              :style="'width:15px;height:15px;'"
              name="svg:search-bt.svg"
            ></SvgIcon>
          </el-button>
        </div>
      </div>
      <div class="table-container">
        <el-table
          v-loading="dataContainer.loading"
          :data="dataContainer.list"
          border
          @cell-dblclick="handleCopyVale"
          @sort-change="handleSortChange"
          height="100%"
        >
          <el-table-column
            align="center"
            label="ID"
            min-width="80"
            fixed="left"
            prop="id"
          />
          <el-table-column
            label="员工ID"
            align="center"
            min-width="120"
            prop="user.employeeId"
          />
          <el-table-column
            label="真实姓名"
            align="center"
            min-width="120"
            prop="user.realName"
          />
          <el-table-column
            label="操作员"
            align="center"
            min-width="120"
            prop="operator"
          />
          <el-table-column label="持续时间" align="center" min-width="120">
            <template #default="scope">
              {{ formatDuration(scope.row.duration) }}
            </template>
          </el-table-column>
          <el-table-column
            label="开始时间"
            align="center"
            min-width="160"
            prop="startTime"
          >
            <template #default="scope">
              {{ formatDateTime(scope.row.startTime) }}
            </template>
          </el-table-column>
          <el-table-column
            label="结束时间"
            align="center"
            min-width="160"
            prop="endTime"
          >
            <template #default="scope">
              {{ formatDateTime(scope.row.endTime) }}
            </template>
          </el-table-column>
          <el-table-column
            label="操作类型"
            align="center"
            min-width="120"
            prop="operationType.name"
          />
          <el-table-column
            label="状态"
            align="center"
            min-width="100"
            prop="status"
          >
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">{{
                scope.row.status
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            align="center"
            min-width="160"
            prop="createdAt"
          >
            <template #default="scope">
              {{ formatDateTime(scope.row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="120"
            fixed="right"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <!-- 移除查看和编辑，如果无对应API -->
              <el-button
                :text="true"
                type="danger"
                @click="handleDelete([scope.row.id])"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-container">
        <el-pagination
          v-show="true"
          :total="dataContainer.config.total"
          :background="true"
          :current-page="dataContainer.params.page"
          :page-size="dataContainer.params.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10, 20, 30, 50]"
          :pager-count="7"
          @size-change="
            (size) => {
              dataContainer.params.limit = size;
              updatePageData();
            }
          "
          @current-change="
            (page) => {
              dataContainer.params.page = page;
              updatePageData();
            }
          "
        />
      </div>
    </div>
    <!-- 移除EditDataDialog如果无编辑 -->
  </div>
</template>

<script>
/**
 * 订单管理页面
 */
import {
  defineComponent,
  onBeforeUnmount,
  ref,
  reactive,
  getCurrentInstance,
  onActivated,
  onMounted,
  watchEffect,
} from "vue";
import ordersApi from "@/http/orders.js";
import { useRouter } from "vue-router";
import { copyValue } from "@/common/OtherTools";
import DictTags from "@/components/DictTags.vue";
import { debounceFn } from "@/common/DebounceAndThrottle";
import { responseData } from "./common/Data.js";
import { messageSuccess, confirm } from "@/action/MessagePrompt.js";
import SvgIcon from "@/components/svgIcon/index.vue";
import { hasPermi } from "@/action/PowerTools";
import systemApi from "@/http/system.js"; // 确认导入
import { ElMessageBox } from "element-plus";

export default defineComponent({
  components: {
    DictTags,
    SvgIcon,
  },
  setup() {
    onMounted(() => {
      getDataList();
    });
    const EditDataDialogRef = ref(null); //组件实例
    const router = useRouter();

    // 日期范围快捷选项
    const dateRangeShortcuts = [
      {
        text: "最近一周",
        value: () => {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
          return [start, end];
        },
      },
      {
        text: "最近一个月",
        value: () => {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
          return [start, end];
        },
      },
      {
        text: "最近三个月",
        value: () => {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
          return [start, end];
        },
      },
    ];

    const dataContainer = reactive({
      loading: false,
      showSearch: true,
      form: {
        employeeId: "",
        operationType: "",
        status: "",
        dateRange: [],
      },
      params: {
        page: 1,
        limit: 10,
      },
      config: {
        total: 0,
      },
      list: [], // 当前页数据
      allData: [], // 所有数据
    });

    /** 获取状态标签类型 */
    function getStatusType(status) {
      switch (status) {
        case "completed":
          return "success";
        // 添加其他状态
        default:
          return "info";
      }
    }

    /** 处理日期范围变化 */
    function handleDateRangeChange(val) {
      if (val) {
        dataContainer.form.startDate = val[0];
        dataContainer.form.endDate = val[1];
      } else {
        dataContainer.form.startDate = undefined;
        dataContainer.form.endDate = undefined;
      }
    }

    /** 获取数据列表 */
    const getDataList = debounceFn(function () {
      dataContainer.loading = true;

      // 构建查询参数（如果API支持过滤）
      const params = {
        // employeeId: dataContainer.form.employeeId,
        // operationType: dataContainer.form.operationType,
        // status: dataContainer.form.status,
        // startDate: dataContainer.form.startDate,
        // endDate: dataContainer.form.endDate,
      };

      systemApi
        .getTimerRecords(params)
        .then((res) => {
          dataContainer.allData = res || [];
          dataContainer.config.total = dataContainer.allData.length;
          updatePageData();
        })
        .catch((err) => {
          console.error("获取计时记录失败", err);
          dataContainer.allData = [];
          dataContainer.list = [];
          dataContainer.config.total = 0;
        })
        .finally(() => {
          dataContainer.loading = false;
        });
    }, 300);

    /** 更新当前页数据 */
    function updatePageData() {
      const start =
        (dataContainer.params.page - 1) * dataContainer.params.limit;
      const end = start + dataContainer.params.limit;
      dataContainer.list = dataContainer.allData.slice(start, end);
    }

    /** 双击单元格，复制单元格内容 */
    function handleCopyVale(_, __, ___, event) {
      copyValue(event.target.innerText);
      messageSuccess("复制成功，内容为：" + event.target.innerText);
    }

    /** 排序触发事件 */
    function handleSortChange(column) {
      // 如果需要客户端排序，实现排序逻辑并更新allData
    }

    /** 搜索按钮操作 */
    function handleQuery() {
      dataContainer.params.page = 1;
      // 如果API不支持服务器端过滤，实现客户端过滤
      // 否则调用getDataList()
      getDataList(); // 假设API支持参数过滤
    }

    /** 重置按钮操作 */
    function resetQuery() {
      dataContainer.form = {
        employeeId: "",
        operationType: "",
        status: "",
        dateRange: [],
      };
      handleQuery();
    }

    /** 删除 */
    function handleDelete(ids) {
      confirm("确认删除该计时记录？")
        .then(() => {
          dataContainer.loading = true;
          systemApi
            .deleteTimerRecord(ids[0])
            .then(() => {
              messageSuccess("删除成功");
              getDataList();
            })
            .catch(() => {
              return;
            })
            .finally(() => {
              dataContainer.loading = false;
            });
        })
        .catch(() => {});
    }

    /** 格式化日期时间 */
    function formatDateTime(dateTime) {
      if (!dateTime) return "-";
      const date = new Date(dateTime);
      return date.toLocaleString();
    }

    /** 格式化持续时间 */
    function formatDuration(seconds) {
      const hours = Math.floor(seconds / 3600);
      const minutes = Math.floor((seconds % 3600) / 60);
      return `${hours}小时${minutes}分钟`;
    }

    return {
      dataContainer,
      getDataList,
      handleCopyVale,
      handleSortChange,
      handleQuery,
      resetQuery,
      getStatusType,
      hasPermi,
      handleDateRangeChange,
      formatDateTime,
      dateRangeShortcuts,
      formatDuration,
      handleDelete, // 保留删除
    };
  },
});
</script>

<style lang="scss" scoped>
.main-view {
  display: flex;
  flex-direction: column;
  > .page-query-box {
    margin: 0 0 10px 0 !important;
    padding: 10px 10px 0px 10px;
    :deep(.el-form-item) {
      margin-bottom: 10px !important;
    }
    :deep(.el-form-item--default) {
      width: 100%;
      margin-right: 0;
    }
  }
  > .content-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    padding: 10px 10px;
    box-sizing: border-box;
    background: #fff;
    > .top-container {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin: 0px 0 10px 0;
    }
    > .table-container {
      flex: 1 1 auto;
      height: 0;
      overflow: auto;
    }
  }
  .pagination-container {
    display: flex;
    justify-content: flex-end;
    padding: 0;
    margin: 10px 0 0 0;
  }
}
</style>
